package com.example.membership.dao.impl;
import com.example.membership.dao.OrderDao;
import com.example.membership.model.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.Date;
import java.util.List;

@Repository
public class OrderDaoImpl implements OrderDao {
    private final JdbcTemplate jdbcTemplate;

    public OrderDaoImpl(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void insert(Order order) {
        String sql = "INSERT INTO orders (user_id, product_id, quantity, shipping_address, payment_method, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                order.getUserId(),
                order.getProductId(),
                order.getQuantity(),
                order.getShippingAddress(),
                order.getPaymentMethod(),
                "已创建", // 默认状态
                new Date() // 当前时间
        );
    }

    @Override
    public void update(Order order) {
        String sql = "UPDATE orders SET status = ? WHERE id = ?";
        jdbcTemplate.update(sql, order.getStatus(), order.getId());
    }

    @Override
    public void delete(int id) {
        String sql = "DELETE FROM orders WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Order> findAll() {
        String sql = "SELECT o.id, o.user_id, o.product_id, o.quantity, o.shipping_address, o.payment_method, o.status, o.created_at, p.name AS product_name " +
                "FROM orders o " +
                "JOIN products p ON o.product_id = p.id";
        return jdbcTemplate.query(sql, orderRowMapper());
    }

    private RowMapper<Order> orderRowMapper() {
        return (rs, rowNum) -> {
            Order order = new Order();
            order.setId(rs.getInt("id"));
            order.setUserId(rs.getInt("user_id"));
            order.setProductId(rs.getInt("product_id"));
            order.setQuantity(rs.getInt("quantity"));
            order.setShippingAddress(rs.getString("shipping_address"));
            order.setPaymentMethod(rs.getString("payment_method"));
            order.setStatus(rs.getString("status"));
            order.setCreatedAt(rs.getDate("created_at"));
            order.setProductName(rs.getString("product_name"));
            return order;
        };
    }
}